package chapter14;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/12 19:22
 */
interface Interface {
    void doSomething();

    void somethingElse(String arg);
}

class RealObject implements Interface {

    @Override
    public void doSomething() {
        System.out.println("doing some thing");
    }

    @Override
    public void somethingElse(String arg) {
        System.out.println("somethingElse " + arg);
    }
}

class SimpleProxy implements InvocationHandler {

    private Object target;

    public SimpleProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("invoke from proxy");
        Object result = method.invoke(target, args);
        if (!(method.getReturnType().isAssignableFrom(void.class))) {
            System.out.println("get result: " + result);
        }
        return result;
    }
}

public class SimpleProxyDemo {


    public static void main(String[] args) {
        SimpleProxy proxy = new SimpleProxy(new RealObject());
        Interface object = (Interface) Proxy.newProxyInstance(SimpleProxyDemo.class.getClassLoader(), new Class<?>[]{Interface.class}, proxy);
        object.doSomething();
        object.somethingElse("haha");
    }
}
